<template>
  <div>
    <!-- excel预览 数据来源：1.线上路径地址 2.本地public路径 3.二进制文件转为dataURL格式-base64-->
    <VueOfficeExcel v-if="excelSrc" :src="excelSrc" style="height: 500px"/>
    <!-- 选择本地excel文件 -->
    <input type="file" @change="fileChange" />
    <!-- 请求接口获取 excel 文件 -->
    <button @click="download">请求接口</button>
    <!-- 将本地或者接口请求到的excel文件 转化成html -->
    <div v-html="_html"></div>
    <!-- 点击下载按钮将excel文件下载到本地 -->
    <a
      href="/api/download"
      download="/api/download"
      >下载</a
    >
    <!-- 将本地或者接口请求到的excel文件 转化成 json 格式数据 -->
    <div>
      {{ JSON.stringify(_json) }}
    </div>
    <!-- 将data数据转化成 excel 文件 并下载到本地 -->
    <button @click="dataToExcel">Data 转化excel</button>
    <!-- 将tableDOM转化成 excel 文件 并下载到本地 -->
    <el-table ref="tableExcel" :data="data" style="width: 100%">
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="id" label="编号" width="180"> </el-table-column>
      <el-table-column prop="score" label="成绩"> </el-table-column>
    </el-table>
    <button @click="tableToExcel">table DOM转化excel</button>
  </div>
</template>

<script setup>
import VueOfficeExcel from '@vue-office/excel'
//引入相关样式
import '@vue-office/excel/lib/index.css'
import { read, writeFile, utils } from "xlsx";
import axios from "axios";
import { ref } from "vue";
import { readFile } from 'vxe-table';

const _html = ref(null);
const _json = ref();
const excelSrc = ref('');

const data = ref([
  { name: "赵倩", id: 1, score: 99 },
  { name: "小学", id: 2, score: 99 },
  { name: "summer", id: 3, score: 100 },
]);
const tableExcel = ref(null);

// 将本地的data数据转化成excel表格
const dataToExcel = () => {
  let _sheetData = utils.json_to_sheet(data.value);
  let wb = utils.book_new();
  utils.book_append_sheet(wb, _sheetData, "sheet1");
  writeFile(wb, "text1.xlsx");
};
// 将table DOM 转化成excel表格
const tableToExcel = () => {
  let _sheetData = utils.table_to_sheet(tableExcel.value.$el);
  let wb = utils.book_new();
  utils.book_append_sheet(wb, _sheetData, "sheet1");
  writeFile(wb, "text2.xlsx");
};

// 将本地导入的excel文件转化成html或者json
const fileChange = (e) => {
  const file = e.target.files[0];
  // blob转为base64
  const fr = new FileReader()
  fr.readAsDataURL(file)
  fr.onload = function() {
    excelSrc.value = fr.result
  }

//   file.arrayBuffer().then((res) => {
//     let wb = read(res);
//     let sheet1 = wb.Sheets.Sheet1;
//     _html.value = utils.sheet_to_html(sheet1);
//     _json.value = utils.sheet_to_json(sheet1);
//   });
};
// 将请求接口得来的excel文件转化成html或者json
const download = async () => {
  const { data } = await axios.get("/api/download", {
    responseType: "blob",
  });
  data.arrayBuffer().then((res) => {
    let wb = read(res);
    let sheet1 = wb.Sheets.Sheet1;
    _html.value = utils.sheet_to_html(sheet1);
    _json.value = utils.sheet_to_json(sheet1);
  });
};
</script>

<style lang="less" scoped></style>
